﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Navigation;

namespace WellDone
{
    public partial class Reports : Page
    {
        bool initialing = false;

        public ObservableCollection<ReportDisplayData> reportDisplayDataSource = new ObservableCollection<ReportDisplayData>();

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            init();
        }

        public Reports()
        {
            InitializeComponent();
            DispatcherTimer t = new DispatcherTimer();
            t.Interval = new TimeSpan(0, 0, 1);
            t.Tick += new EventHandler(RefreshData);
            t.Start();
            // Hide the UI
            lblReportsGenerating.Visibility = Visibility.Collapsed;
            btnCancel.Visibility = Visibility.Collapsed;
            lblFrequency.Visibility = Visibility.Collapsed;
            lblGenerated.Visibility = Visibility.Collapsed;
            lblGeneratedDate.Visibility = Visibility.Collapsed;
            lblName.Visibility = Visibility.Collapsed;
            lblReport.Visibility = Visibility.Collapsed;
            lblReportDate.Visibility = Visibility.Collapsed;
            cmbReportFrequency.Visibility = Visibility.Collapsed;
            cmbReportName.Visibility = Visibility.Collapsed;
            btnExport.Visibility = Visibility.Collapsed;
            btnGenerate.Visibility = Visibility.Collapsed;
            btnPrint.Visibility = Visibility.Collapsed;
            dgReport.Visibility = Visibility.Collapsed;
            lblGeneratedBy.Visibility = Visibility.Collapsed;
            lblGeneratedByUser.Visibility = Visibility.Collapsed;
        }

        private async void RefreshData(object sender, EventArgs e)
        {
            if (Globals.mainPage.ContentFrame.Content != null && Globals.reports != null)
                if (Globals.mainPage.ContentFrame.Content.GetType() == Globals.reports.GetType())
                {
                    // Determine if reports are being generated
                    if (await Globals.db.ReportsGenerating())
                    {
                        // Hide the UI
                        lblReportsGenerating.Visibility = Visibility.Visible;
                        btnCancel.Visibility = Visibility.Visible;
                        lblFrequency.Visibility = Visibility.Collapsed;
                        lblGenerated.Visibility = Visibility.Collapsed;
                        lblGeneratedDate.Visibility = Visibility.Collapsed;
                        lblName.Visibility = Visibility.Collapsed;
                        lblReport.Visibility = Visibility.Collapsed;
                        lblReportDate.Visibility = Visibility.Collapsed;
                        cmbReportFrequency.Visibility = Visibility.Collapsed;
                        cmbReportName.Visibility = Visibility.Collapsed;
                        btnExport.Visibility = Visibility.Collapsed;
                        btnGenerate.Visibility = Visibility.Collapsed;
                        btnPrint.Visibility = Visibility.Collapsed;
                        dgReport.Visibility = Visibility.Collapsed;
                        lblGeneratedBy.Visibility = Visibility.Collapsed;
                        lblGeneratedByUser.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        // Show the UI
                        lblReportsGenerating.Visibility = Visibility.Collapsed;
                        btnCancel.Visibility = Visibility.Collapsed;
                        lblFrequency.Visibility = Visibility.Visible;
                        lblGenerated.Visibility = Visibility.Visible;
                        lblGeneratedDate.Visibility = Visibility.Visible;
                        lblName.Visibility = Visibility.Visible;
                        lblReport.Visibility = Visibility.Visible;
                        lblReportDate.Visibility = Visibility.Visible;
                        cmbReportFrequency.Visibility = Visibility.Visible;
                        cmbReportName.Visibility = Visibility.Visible;
                        btnExport.Visibility = Visibility.Visible;
                        btnGenerate.Visibility = Visibility.Visible;
                        btnPrint.Visibility = Visibility.Visible;
                        dgReport.Visibility = Visibility.Visible;
                        lblGeneratedBy.Visibility = Visibility.Visible;
                        lblGeneratedByUser.Visibility = Visibility.Visible;
                    }
                }
        }
  
        // Executes when the user navigates to this page.
        public void init()
        {
            Globals.showWaitCursor(true);
            RefreshData(null,null);
            initialing = true;
            cmbReportFrequency.Items.Clear();
            cmbReportFrequency.Items.Add("Daily");
            cmbReportFrequency.Items.Add("Weekly");
            cmbReportFrequency.Items.Add("Monthly");
            cmbReportFrequency.SelectedIndex = 0;
            // Load report information...
            initReportNameComboBox();
            initialing = false;
            Globals.reports = this;
            Globals.showWaitCursor(false);
        }

        public async void initReportNameComboBox()
        {
            if(cmbReportName.Items!=null) cmbReportName.Items.Clear();
            char freq = (cmbReportFrequency.SelectedIndex == 0 ? 'D' : (cmbReportFrequency.SelectedIndex == 1 ? 'W' : 'M'));
            await Globals.db.GetReportObjects("Frequency='" + freq + "' order by Name");
            foreach (ServiceReferenceOpenRPOS.Report report in Globals.db.ReportRecords)
            {
                cmbReportName.Items.Add(report.col_Name);
            }
            if (cmbReportName.Items.Count > 0)
                cmbReportName.SelectedIndex = 0;
        }

        public async void initReportGrid()
        {
            Globals.showWaitCursor(true);
            // Get column headers and report data for selected report
            await Globals.db.GetReportHeaderObjects("ReportID=" + Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ID.ToString() + " order by ColumnNumber");
            await Globals.db.GetReportDataObjects("ReportID=" + Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ID.ToString() + " order by RowNumber");
            await Globals.db.GetLoginObjects("ID=" + Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_GeneratedByLoginID.ToString());
            reportDisplayDataSource.Clear();
            lblReportDate.Content = Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ReportDate.ToShortDateString();
            lblGeneratedDate.Content = Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_GeneratedDate.ToString();
            if (Globals.db.LoginRecords.Count > 0) lblGeneratedByUser.Content = Globals.db.LoginRecords[0].col_DisplayName; else lblGeneratedByUser.Content = ""; 
            // Setup the headers
            for (int i = 0; i <= 5; i++)
            {
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > i)
                {
                    dgReport.Columns[i].Visibility = Visibility.Visible;
                    dgReport.Columns[i].Header = Globals.db.ReportHeaderRecords[i].col_ColumnName;
                }
                else
                    dgReport.Columns[i].Visibility = Visibility.Collapsed;
            }
            // Populate the data grid
            foreach (ServiceReferenceOpenRPOS.ReportData reportDataRecord in Globals.db.ReportDataRecords)
            {
                ReportDisplayData reportDisplayDataRecord = new ReportDisplayData()
                    {
                        Column0 = reportDataRecord.col_Column0,
                        Column1 = reportDataRecord.col_Column1,
                        Column2 = reportDataRecord.col_Column2,
                        Column3 = reportDataRecord.col_Column3,
                        Column4 = reportDataRecord.col_Column4,
                        Column5 = reportDataRecord.col_Column5
                    };
                reportDisplayDataSource.Add(reportDisplayDataRecord);
            }
            dgReport.ItemsSource = reportDisplayDataSource;
            Globals.showWaitCursor(false);
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void cmbReportName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Re-initialize the report
            if (cmbReportName.SelectedIndex >= 0)
                initReportGrid();
        }

        private void cmbReportFrequency_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Re-initialize the report name combo box
            if (cmbReportName != null && !initialing) initReportNameComboBox();
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            // Print the current report
            string strReportTitle = (cmbReportFrequency.SelectedIndex == 0 ? "Daily" : (cmbReportFrequency.SelectedIndex == 1 ? "Weekly" : "Monthly")) + " - " +
                Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_Name + " " +
                Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ReportDate.ToShortDateString().Replace("/","-");
            Globals.Print(dgReport, strReportTitle, false);
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            string contents="";
            // Initailize the contents
            foreach (ServiceReferenceOpenRPOS.ReportHeader reportHeader in Globals.db.ReportHeaderRecords)
            {
                contents += reportHeader.col_ColumnName + ",";
            }
            contents = contents.Substring(0, contents.Length - 1) + "\r\n";

            // Add the report data
            foreach (ServiceReferenceOpenRPOS.ReportData reportData in Globals.db.ReportDataRecords)
            {
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 0)
                    contents += "\"" + reportData.col_Column0 + "\",";
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 1)
                    contents += "\"" + reportData.col_Column1+ "\",";
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 2)
                    contents += "\"" + reportData.col_Column2 + "\",";
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 3)
                    contents += "\"" + reportData.col_Column3 + "\",";
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 4)
                    contents += "\"" + reportData.col_Column4 + "\",";
                if (Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ColumnCount > 5)
                    contents += "\"" + reportData.col_Column5 + "\",";
                contents = contents.Substring(0, contents.Length - 1) + "\r\n";
            }

            // Present the dialog for saving data
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = "csv";
            sfd.Filter = "CSV files (*.csv)|*.csv|Text files (*.txt)|*.txt|All files (*.*)|*.*";
            sfd.DefaultFileName = (cmbReportFrequency.SelectedIndex == 0 ? "Daily" : (cmbReportFrequency.SelectedIndex == 1 ? "Weekly" : "Monthly")) + " - " +
                Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_Name + " " + 
                Globals.db.ReportRecords[cmbReportName.SelectedIndex].col_ReportDate.ToShortDateString().Replace("/","-") + ".csv";
            if (sfd.ShowDialog() == true)
            {
                using (StreamWriter stream = new StreamWriter(sfd.OpenFile()))
                {
                    stream.Write(contents);
                    stream.Close();
                }
            }
        }

        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            GenerateReportsDialog grd = new GenerateReportsDialog();
            grd.init();
            grd.Show();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            // Cancel report generation
            Globals.db.CancelReportGeneration();
        }

    }

    public class ReportDisplayData
    {
        public string Column0 { get; set; }
        public string Column1 { get; set; }
        public string Column2 { get; set; }
        public string Column3 { get; set; }
        public string Column4 { get; set; }
        public string Column5 { get; set; }
    }

}
